<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace buwang\middleware;

use buwang\interfaces\MiddlewareInterface;
use buwang\traits\JsonTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use buwang\traits\JumpTrait;
use app\Request;
use buwang\service\AuthService;
use buwang\exception\AuthException;

/**
 * 系统权限访问管理
 * Class Auth
 * @package app\admin\middleware
 */
class Auth implements MiddlewareInterface
{
    use JsonTrait;
    use JumpTrait;

    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function handle(Request $request, \Closure $next)
    {
        $node_name = '/' . app('http')->getName() . '/' . $request->rule()->getRoute();

        //获取管理员信息
        $user = $request->userInfo();//解析token,获取用户信息

        //获取登录类型
        $login_type = $request->scopes();

        if ($user) {
         try{
             AuthService::auth($user,$login_type,$node_name);
         }catch (AuthException $e){
             if ($request->isAjax()) return $this->code(403)->error($e->getMessage());//ajax请求返回code
              else return $this->error_jump($e->getMessage());//模板解析时重定向至登录页面
         }
        }

        return $next($request);
    }
}
